package main

import (
	"context"
	"flag"
	"gitee.com/man0sions/IdCreator/core"
	"gitee.com/man0sions/IdCreator/service/rpc"
	"gitee.com/man0sions/IdCreator/service/thttp"
	"log"
	"os"
	"os/signal"
	"syscall"
)

var (
	err    error
	conf   = flag.String("conf", "./config/main.yaml", "conf file")
	nodeId = flag.Int64("nodeId", 20, "nodeId")
)

func init() {
	log.SetFlags(log.Lshortfile)
}

func start(ctx context.Context) {

	if err = core.NewLogger(core.GConfig.Log); err != nil {
		log.Panicln(err)
	}
	if _, err = core.NewSnowFlake(*nodeId); err != nil {
		log.Panicln(err)
	}
	engine := thttp.NewHttpServer(core.GConfig.Viper, thttp.InitRouter)
	go rpc.NewRpc(engine, core.GConfig.Viper, "Id_Creator")

}
func main() {
	flag.Parse()

	ctx, cancel := context.WithCancel(context.TODO())

	if err = core.InitConfig(*conf); err != nil {
		log.Panicln(err)
	}
	start(ctx)

	exitChan := make(chan os.Signal)
	signal.Notify(exitChan, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGSTOP, syscall.SIGTERM)

	for {
		select {
		case <-exitChan:
			log.Println("bye ...")
			cancel()
			thttp.StopHttpServer()
			os.Exit(0)
		}
	}
}
